import { onMounted, ref } from 'vue';
import { userLoginApi, getVerifyCode } from '../../api/login.js';
import { userStore } from '../../store/user.js';

export function useAccountLogin(loginForm) {
  const { saveUserInfo, savePwd } = userStore();
  const loading = ref(false);
  const ruleFormRef = ref(null);

  const verifyImage = ref(null);
  function userLogin() {
    ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          loading.value = true;
          const data = await userLoginApi(loginForm);
          data.data.code ? afterLogin(data): await getVerifyCodeData()
          loading.value = false;
        } catch (err) {
          loading.value = false;
        }
      } else {
        return false;
      }
    });
  }
  function afterLogin(userLoginInfo) {
    if (userLoginInfo.data.code === 1) {
      saveUserInfo(userLoginInfo, loginForm);
      window.location.hash = '/';
    }
  }
  // 保存密码
  function savePwsChange(val) {
    val && savePwd(val);
  }
  // 获取验证吗
  async function getVerifyCodeData() {
    const res = await getVerifyCode();
    verifyImage.value = window.URL.createObjectURL(res.data);
  }
  onMounted(() => {
    getVerifyCodeData().then((r) => {});
  });
  return {
    userLogin,
    savePwsChange,
    loading,
    verifyImage,
    getVerifyCodeData,
    ruleFormRef,
  };
}
